package com.february.todo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.february.todo.tools.Bean_todo;
import com.february.todo.tools.NavigateBar;
import com.february.todo.tools.TimeComparator;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AddTodoActivity extends AppCompatActivity {

    private static final String[] PERMISSIONS = {
            "android.permission.READ_EXTERNAL_STORAGE"
            , "android.permission.WRITE_EXTERNAL_STORAGE"
            , "android.permission.CAMERA"};

    TextView tv_date;
    TextView tv_timeStart;
    TextView tv_timeEnd;
    EditText et_title;
    EditText et_detail;
    ImageView iv_photo;
    Button btn_confirm;
    Button btn_photo;
    Button btn_cancel;
    Button btn_state;
    Bean_todo bean_todo;
    Date timeStart;
    int isFinished;
    boolean isUpdate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_todo);

        ActivityCompat.requestPermissions(AddTodoActivity.this, PERMISSIONS, 1);

        tv_date = findViewById(R.id.tv_date);
        tv_timeStart = findViewById(R.id.tv_timeStart);
        tv_timeEnd = findViewById(R.id.tv_timeEnd);
        et_title = findViewById(R.id.et_title);
        et_detail = findViewById(R.id.et_detail);
        iv_photo = findViewById(R.id.iv_photo);
        btn_confirm = findViewById(R.id.btn_confirm);
        btn_photo = findViewById(R.id.btn_photo);
        btn_cancel = findViewById(R.id.btn_cancel);
        btn_state = findViewById(R.id.btn_state);


        bean_todo = (Bean_todo) getIntent().getSerializableExtra("bean_todo");

        isUpdate = (bean_todo != null);
        if (isUpdate) {
            et_title.setText(bean_todo.getTitle());
            et_detail.setText(bean_todo.getDetail());
            if (bean_todo.getPhotoPath() != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(bean_todo.getPhotoPath());
                iv_photo.setImageBitmap(bitmap);
                iv_photo.setRotation(90);
            }
        } else {
            bean_todo = new Bean_todo();
        }
        init_tv_date();
        init_tv_timeStart();
        init_tv_timeEnd();
        init_btn_photo();
        init_btn_confirm();
        init_btn_cancel();
        init_btn_state();
    }

    private void init_tv_date() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-d", Locale.CHINA); //设置时间格式
        Date date = null;
        if (isUpdate) {
            try {
                date = formatter.parse(bean_todo.getDate());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            date = new Date(System.currentTimeMillis()); //获取当前时间
        }

        assert date != null;
        assert bean_todo != null;
        bean_todo.setDate(formatter.format(date));
        tv_date.setText(bean_todo.getDate());

        tv_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerBuilder(AddTodoActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        bean_todo.setDate(formatter.format(date));
                        tv_date.setText(bean_todo.getDate());
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})//分别对应年月日时分秒，默认全部显示
                        .isDialog(true)
                        .build();

                Dialog mDialog = pvTime.getDialog();
                if (mDialog != null) {

                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            Gravity.BOTTOM);

                    params.leftMargin = 0;
                    params.rightMargin = 0;
                    pvTime.getDialogContainerLayout().setLayoutParams(params);

                    Window dialogWindow = mDialog.getWindow();
                    if (dialogWindow != null) {
                        dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                        dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                    }
                }
                pvTime.show();
            }
        });
    }

    private void init_tv_timeStart() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.CHINA); //设置时间格式
        Date time = null;
        if (isUpdate) {
            try {
                time = formatter.parse(bean_todo.getTimeStart());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            time = new Date(System.currentTimeMillis()); //获取当前时间
        }
        timeStart = time;
        assert time != null;
        bean_todo.setTimeStart(formatter.format(time));
        tv_timeStart.setText(bean_todo.getTimeStart());
        tv_timeStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerBuilder(AddTodoActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        if (new TimeComparator(timeStart, date).isLater) {
                            date.setTime(timeStart.getTime() + 60000);
                        }
                        timeStart = date;
                        bean_todo.setTimeStart(formatter.format(date));
                        tv_timeStart.setText(bean_todo.getTimeStart());
                    }
                })
                        .setType(new boolean[]{false, false, false, true, true, false})//分别对应年月日时分秒，默认全部显示
                        .isDialog(true)
                        .build();

                Dialog mDialog = pvTime.getDialog();
                if (mDialog != null) {

                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            Gravity.BOTTOM);

                    params.leftMargin = 0;
                    params.rightMargin = 0;
                    pvTime.getDialogContainerLayout().setLayoutParams(params);

                    Window dialogWindow = mDialog.getWindow();
                    if (dialogWindow != null) {
                        dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                        dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                    }
                }
                pvTime.show();
            }
        });
    }

    private void init_tv_timeEnd() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm", Locale.CHINA); //设置时间格式
        Date time = null;
        if (isUpdate) {
            try {
                time = formatter.parse(bean_todo.getTimeEnd());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            time = new Date(System.currentTimeMillis() + 1800000);
        }
        assert time != null;
        bean_todo.setTimeEnd(formatter.format(time));
        tv_timeEnd.setText(bean_todo.getTimeEnd());
        tv_timeEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerBuilder(AddTodoActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        if (new TimeComparator(timeStart, date).isLater) {
                            date.setTime(timeStart.getTime() + 60000);
                        }
                        bean_todo.setTimeEnd(formatter.format(date));
                        tv_timeEnd.setText(bean_todo.getTimeEnd());
                    }
                })
                        .setType(new boolean[]{false, false, false, true, true, false})//分别对应年月日时分秒，默认全部显示
                        .isDialog(true)
                        .build();

                Dialog mDialog = pvTime.getDialog();
                if (mDialog != null) {

                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            Gravity.BOTTOM);

                    params.leftMargin = 0;
                    params.rightMargin = 0;
                    pvTime.getDialogContainerLayout().setLayoutParams(params);

                    Window dialogWindow = mDialog.getWindow();
                    if (dialogWindow != null) {
                        dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                        dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                    }
                }
                pvTime.show();
            }
        });
    }

    private void init_btn_photo() {
        btn_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddTodoActivity.this, TakePhotoActivity.class);
                startActivityForResult(intent, 1);
            }
        });
    }

    private void init_btn_state() {
        if (bean_todo.getState() == 2) {
            isFinished = 1;
            btn_state.setText("已完成");
            btn_state.setBackgroundResource(R.color.green);
        } else {
            isFinished = 0;
            btn_state.setText("未完成");
            btn_state.setBackgroundResource(R.color.grey);
        }

        btn_state.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFinished == 0) {
                    isFinished = 1;
                    btn_state.setText("已完成");
                    btn_state.setBackgroundResource(R.color.green);
                } else {
                    isFinished = 0;
                    btn_state.setText("未完成");
                    btn_state.setBackgroundResource(R.color.grey);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                String filename = data.getStringExtra("filename");
                bean_todo.setPhotoPath("/storage/emulated/0/Pictures/" + filename + ".jpg");
                Bitmap bitmap = BitmapFactory.decodeFile(bean_todo.getPhotoPath());
                iv_photo.setImageBitmap(bitmap);
                iv_photo.setRotation(90);
            }
        }
    }

    private void init_btn_confirm() {
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bean_todo.setTitle(et_title.getText().toString());
                bean_todo.setDetail(et_detail.getText().toString());

                if (isFinished == 0) {
                    if (new TimeComparator(bean_todo.getDate(), bean_todo.getTimeEnd()).isEarlier) {
                        bean_todo.setState(1);
                    } else {
                        bean_todo.setState(0);
                    }
                } else {
                    bean_todo.setState(2);
                }

                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean_todo", bean_todo);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    private void init_btn_cancel() {
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(RESULT_CANCELED, intent);
                finish();
            }
        });
    }
}